package com.example.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import lombok.extern.slf4j.Slf4j;
@Slf4j
@Controller
public class UploadController {

    /**
     * 在配置文件中配置的文件保存路径
     */
    @Value("${flycatAdmin.filePath}")
    private String myFilePath;
    	    
	@GetMapping("/")
	public String index() {
		return "upload";
	}
	
	@GetMapping("/index")
	public String update() {
		return "upload";
	}

	@PostMapping("/upload")
	public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
		if (file.isEmpty()) {
			redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
			return "redirect:uploadStatus";
		}

		try {
			byte[] bytes = file.getBytes();
			File myPath = new File(myFilePath);  
            if (!myPath.exists()){ 
                myPath.mkdirs();
            }
            String fileName =file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
	        fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+suffix;
			Path path = Paths.get(myFilePath + fileName);
			Files.write(path, bytes);
			redirectAttributes.addFlashAttribute("message","You successfully uploaded 【" + path.getParent().toString()+ "】");
		} catch (IOException e) {
			log.error("程序异常："+e.getMessage(),e);
			e.printStackTrace();
		}
		return "redirect:/uploadStatus";
	}

	@GetMapping("/uploadStatus")
	public String uploadStatus() {
		return "uploadStatus";
	}

}